package ren.nearby.main.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by Administrator on 2017/9/19 0019.
 */

public class PlayService extends Service implements MediaPlayer.OnCompletionListener, AudioManager.OnAudioFocusChangeListener {
    private static final long TIME_UPDATE = 100L;
    private IntentFilter mNoisyFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    private NoisyAudioStreamReceiver mNoisyReceiver = new NoisyAudioStreamReceiver();
    //音乐播放集合
    private List<Music> mMusicList;
    //音乐监听回调实现
    private OnPlayerEventListener mListener;
    //音频管理器 声音 通话 铃声 音乐 闹钟 耳机插入 广播接收器
    private AudioManager mAudioManager;
    // 正在播放的歌曲[本地|网络]
    private Music mPlayingMusic;
    // 正在播放的本地歌曲的序号
    private int mPlayingPosition;
    private boolean isPausing;
    private boolean isPreparing;
    private long quitTimerRemain;
    private MediaPlayer mPlayer = new MediaPlayer();
    private Handler mHandler = new Handler();

    @Override
    public void onCreate() {
        super.onCreate();
        mMusicList = new ArrayList<>();
        mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        mPlayer.setOnCompletionListener(this);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new PlayBinder();
    }

    public static void startCommand(Context context, String action) {
        Intent intent = new Intent(context, PlayService.class);
        intent.setAction(action);
        context.startService(intent);
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && intent.getAction() != null) {
            switch (intent.getAction()) {
                case Actions.ACTION_MEDIA_PLAY_PAUSE:
                    break;
                case Actions.ACTION_MEDIA_NEXT:
                    break;
                case Actions.ACTION_MEDIA_PREVIOUS:
                    break;
            }
        }
        return START_NOT_STICKY;
    }

    public OnPlayerEventListener getOnPlayerEventListener() {
        return mListener;
    }

    public void setOnPlayerEventListener(OnPlayerEventListener listener) {
        mListener = listener;
    }


    @Override
    public void onAudioFocusChange(int focusChange) {
        switch (focusChange) {
            case AudioManager.AUDIOFOCUS_LOSS:
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                pause();//暂停
                break;
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        next();//下一首
    }

    /**
     * 1.播放
     * 2.暂停播放
     * 3.继续播放
     * 4.下一首
     * 5.上一首
     * 6.跳转指定时间位置
     * 7.播放计时定时关闭
     */
    public void play(int position) {
        if (mMusicList.isEmpty()) {
            return;
        }
        if (position < 0) {
            position = mMusicList.size() - 1;
        } else if (position >= mMusicList.size()) {
            position = 0;
        }
        mPlayingPosition = position;
        Music music = mMusicList.get(mPlayingPosition);
        //临时存储播放id

        play(music);
    }

    public void play(Music music) {
        mPlayingMusic = music;
        try {
            //重置
            mPlayer.reset();
            //设置播放源
            mPlayer.setDataSource(music.getPath());
            //异步处理
            mPlayer.prepareAsync();
            isPreparing = true;
            mPlayer.setOnPreparedListener(mPreparedListener);
            if (mListener != null) {
                mListener
                        .onChange(music);
            }
            //通知栏显示。
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void playPause() {
        if (isPreparing()) {
            return;
        }
        if (isPlaying()) {
            pause();//暂停

        } else if (isPausing()) {
            resume();//重置
        } else {
            play(getPlayingPosition());
        }
    }

    public void pause() {
        if (!isPlaying()) {
            return;
        }
        mPlayer.pause();
        isPausing = true;
        mHandler.removeCallbacks(mBackgroundRunnable);
        //显示通知栏
        mAudioManager.abandonAudioFocus(this);
        unregisterReceiver(mNoisyReceiver);
        if (mListener != null) {
            mListener.onPlayerPause();
        }
    }

    private void resume() {
        if (!isPausing()) {
            return;
        }
        start();
        if (mListener != null) {
            mListener.onPlayerResume();
        }
    }

    public void next() {
        if (mMusicList.isEmpty()) {
            return;
        }
        //从缓存取
        PlayModeEnum mode = PlayModeEnum.valueOf(1);
        switch (mode) {
            case SHUFFLE:
                mPlayingPosition = new Random().nextInt(mMusicList.size());
                play(mPlayingPosition);
                break;
            case SINGLE:
                play(mPlayingPosition);
                break;
            case LOOP:
            default:
                play(mPlayingPosition + 1);
                break;
        }
    }

    public void prev() {
        if (mMusicList.isEmpty()) {
            return;
        }
        //从缓存取
        PlayModeEnum mode = PlayModeEnum.valueOf(1);
        switch (mode) {
            case SHUFFLE:
                mPlayingPosition = new Random().nextInt(mMusicList.size());
                play(mPlayingPosition);
                break;
            case SINGLE:
                play(mPlayingPosition);
                break;
            case LOOP:
            default:
                play(mPlayingPosition - 1);
                break;
        }
    }

    private void start() {
        mPlayer.start();
        isPausing = false;
        //操作更新进度
        mHandler.post(mBackgroundRunnable);
        //显示通知栏
        //来电 与 耳机拔出暂停
        mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
        registerReceiver(mNoisyReceiver, mNoisyFilter);
    }

    /**
     * 跳转到指定的时间位置
     *
     * @param mesc 时间
     */
    public void seekTo(int mesc) {
        if (isPlaying() || isPausing()) {
            mPlayer.seekTo(mesc);
            if (mListener != null) {
                mListener.onPublish(mesc);
            }
        }

    }

    /**
     * 更新 删除 或者 下载 正在播放的本地歌曲的序号
     */
    public void updatePlayingPosition() {
        int position = 0;
        long id = 1;//取缓存
        for (int i = 0; i < mMusicList.size(); i++) {
            if (mMusicList.get(i).getId() == id) {
                position = i;
                break;
            }
        }
        mPlayingPosition = position;
        //临时存储当前播放的序号
    }

    /**
     * 扫描音乐
     */
    public void updateMusicList() {
        Logger.e("updateMusicList");
        MusicUtils.scanMusic(this, mMusicList);
        if (!mMusicList.isEmpty()) {
            updatePlayingPosition();
            mPlayingMusic = (mPlayingMusic == null) ? mMusicList.get(mPlayingPosition) : mPlayingMusic;
            Logger.e("进入");
        }
        Logger.e("结束");
    }


    private Runnable mBackgroundRunnable = new Runnable() {
        @Override
        public void run() {
            if (isPlaying() && mListener != null) {
                mListener.onPublish(mPlayer.getCurrentPosition());
            }
            mHandler.postDelayed(this, TIME_UPDATE);
        }
    };
    private MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            isPreparing = false;
            start();
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    public boolean isPlaying() {
        return mPlayer != null && mPlayer.isPlaying();
    }

    public boolean isPausing() {
        return mPlayer != null && isPausing;
    }

    public boolean isPreparing() {
        return mPlayer != null && isPreparing;
    }

    /**
     * 获取正在播放的本地歌曲的序号
     */
    public int getPlayingPosition() {
        return mPlayingPosition;
    }

    /**
     * 获取正在播放的歌曲[本地|网络]
     */
    public Music getPlayingMusic() {
        return mPlayingMusic;
    }

    public class PlayBinder extends Binder {
        public PlayService getService() {
            return PlayService.this;
        }
    }
}
